﻿// Microsoft Public License (Ms-PL)
// nRoute v5 (http://nroute.codeplex.com)
// Modifié par So@t

using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Interactivity;
using CPN.PJN.Silverlight.UI.Interactions.Interactivity;

namespace CPN.PJN.Silverlight.UI.Interactions.Triggers
{
    public class ValueRegexTrigger : TriggerBase<FrameworkElement>
    {

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(string), typeof(ValueRegexTrigger),
            new PropertyMetadata(null, new PropertyChangedCallback(OnSourceChanged)));

        public static readonly DependencyProperty PatternProperty =
            DependencyProperty.Register("Pattern", typeof(string), typeof(ValueRegexTrigger),
            new PropertyMetadata(null));

        #region Properties

        //[TypeConverter(typeof(ConvertFromStringConverter))]
        public string Source
        {
            get { return Convert.ToString(GetValue(SourceProperty)); }
            set { SetValue(SourceProperty, value); }
        }

        public string Pattern
        {
            get { return Convert.ToString(GetValue(PatternProperty)); }
            set { SetValue(PatternProperty, value); }
        }

        public bool Negate { get; set; }

        #endregion

        #region Handlers

        static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ValueRegexTrigger)d).MatchValue(e.NewValue);
        }

        void MatchValue(object sourceValue)
        {
            // basic checks
            if (string.IsNullOrEmpty(Pattern)) return;

            // get the value n' match
            var _matchValue = Convert.ToString(sourceValue);
            var _result = Regex.IsMatch(_matchValue, Pattern);

            // negate, n' invoke
            if (Negate) _result = !_result;
            if (_result) base.InvokeActions(sourceValue);
        }

        #endregion

    }
}
